﻿#include "linuxsystemmethod.h"

QString CPU;//CPU
QString Memory;//内存
QString Disk;//磁盘
QString UpNetword;//网络
QString DoNetword;//网络
QString readDisk;//磁盘读取
QString writeDisk;//磁盘写入
QString NetwordName;//
LinuxSystemMethod::LinuxSystemMethod()
{

}
bool LinuxSystemMethod::getCpuInfo() {
    QProcess process;
    process.start("cat /proc/stat");
    process.waitForFinished();

    // Read all lines from the process
    QByteArray result = process.readAllStandardOutput();
    QString str(result);

    // Split the content into lines
    QStringList lines = str.split("\n", QString::SkipEmptyParts);

    // Process the first line (total CPU stats)
    if (lines.size() > 0) {
        QString line = lines[0];
        QStringList values = line.split(QRegExp("\\s+"), QString::SkipEmptyParts);

        if (values.size() > 8) {
            // Extract CPU states
            double user = values[1].toDouble();
            double nice = values[2].toDouble();
            double system = values[3].toDouble();
            double idle = values[4].toDouble();
            double iowait = values[5].toDouble();
            double irq = values[6].toDouble();
            double softirq = values[7].toDouble();

            // Calculate total and used CPU
            double total = user + nice + system + idle + iowait + irq + softirq;
            double used = user + nice + system;

            // Calculate CPU usage percentage
            double cpuUsage = (used / total) * 100.0;

            qDebug() << "CPU Usage:" << QString::number(cpuUsage, 'f', 2) << "%";
            CPU=QString::number(int(cpuUsage));
            return true;
        }
    }
    return false;
}

bool LinuxSystemMethod::getNetUsage() {
    QProcess process;
    process.start("cat /proc/net/dev");
    process.waitForFinished();

    // Skip the first two lines (header lines)
    process.readLine();
    process.readLine();
    double m_recv_bytes__ = 0.0;
    double m_send_bytes__ = 0.0;
    //double m_timer_interval__ = 0.0;
    while (!process.atEnd()) {
        QString str = process.readLine();
        str.replace("\n", "");
        str.replace(QRegExp("( ){1,}"), " ");

        auto lst = str.split(" ");
        //  if (lst.size() > 9 && lst[0] == "enp8s0:") {
        if(lst.size() > 9 && lst[0] == NetwordName/*"enx00e04c368c30:"*/)
        {
            double recv = 0.0;
            double send = 0.0;
            if(lst.size() > 1)
                recv = lst[1].toDouble();
            if(lst.size() > 9)
                send = lst[9].toDouble();
            qDebug("%s 接收速度:%.0lfmb/s 发送速度:%.0lfmb/s",lst[0].toStdString().c_str(),recv/ 1024000.0,send/ 1024000.0);
            m_recv_bytes__ = recv / 1024000.0;
            m_send_bytes__ = send / 1024000.0;

            UpNetword=QString("%1 mb/s").arg(QString::number(m_recv_bytes__, 'f', 2));
            DoNetword=QString("%1 mb/s").arg(QString::number(m_recv_bytes__, 'f', 2));
        }
        // }
    }

    return true;
}

bool LinuxSystemMethod::getDiskSpeed() {

    double m_disk_read__ = 0.0;
    double m_disk_write__ = 0.0;
    QProcess process;
    process.start("vmstat");
    process.waitForFinished();
    process.readLine(); // Skip the header line
    process.readLine(); // Skip the header line
    QString str = process.readLine();
    qDebug()<<str;
    str.replace("\n", "");
    str.replace(QRegExp("( ){1,}"), " ");
    auto lst = str.split(" ");

    if (lst.size() > 15)

    {
        // Adjust the index based on the actual output of vmstat -d
        qDebug("读取:%.0lfmb/s 写入:%.0lfmb/s", (lst[9].toDouble() - m_disk_read__) , (lst[10].toDouble() - m_disk_write__));
        m_disk_read__ = lst[9].toDouble();
        m_disk_write__ = lst[10].toDouble();
//        UpNetword=QString::number(m_disk_read__);
//        DoNetword=QString::number(m_disk_write__);
        readDisk=QString("%1mb/s").arg(QString::number(m_disk_read__));
        writeDisk=QString("%1mb/s").arg(QString::number(m_disk_write__));
        return true;
    }

    return false;
}
QString LinuxSystemMethod::getDiskSpace(QString Path) {
   QThread::msleep(3000);
    QProcess process;
    process.start("df -k");
    if (!process.waitForFinished()) {
        qDebug() << "Failed to execute df command.";
        return "";
    }

    process.readLine(); // Skip the header line
    while (!process.atEnd()) {
        QString str = process.readLine();
qInfo() << "getDiskSpace."<<str;
        if (str.startsWith(Path)) {
            str.replace("\n", "");
            str.replace(QRegExp("( ){1,}"), " ");

            auto lst = str.split(QRegExp("\\s+"));


            if (lst.size() > 5) {

                return lst[5].toStdString().c_str();

            }
        }
    }

    return "";
}
bool LinuxSystemMethod::getPathSpace(QString Path) {
  // QThread::msleep(500);
    QProcess process;
    process.start("df");
    if (!process.waitForFinished()) {
        qDebug() << "Failed to execute df command.";
        return false;
    }

    process.readLine(); // Skip the header line
    while (!process.atEnd()) {
        QString str = process.readLine();
         qDebug() << "磁盘路径:" << str;
        if (str.contains(Path)) {
            str.replace("\n", "");
            str.replace(QRegExp("( ){1,}"), " ");

            auto lst = str.split(QRegExp("\\s+"));


            if (lst.size() > 5) {
                qDebug() << "磁盘路径:" << lst[5].toStdString().c_str()
                            << "总量:" << lst[1].toDouble() / 1024.0/ 1024.0 << "MB"
                         << "已用:" << lst[2].toDouble() / 1024.0/ 1024.0 << "MB"
                         << "空闲:" << lst[3].toDouble() / 1024.0/ 1024.0 << "MB";

                Disk=QString("%1/%2 TB").arg(QString::number(lst[3].toDouble() / 1024.0/ 1024.0/1024.0, 'f', 2)).arg(QString::number(lst[1].toDouble() / 1024.0/ 1024.0/1024.0, 'f', 2));
                    return true;
            }
        }
    }

    return false;
}
bool LinuxSystemMethod::getMemUsage()
{
    QProcess process;
    process.start("free -m"); //使用free完成获取
    process.waitForFinished();
    process.readLine();
    QString str = process.readLine();
    str.replace("\n","");
    str.replace(QRegExp("( ){1,}")," ");//将连续空格替换为单个空格 用于分割
    auto lst = str.split(" ");
    if(lst.size() > 6)
    {
         double Memory_ = 0.0;
        qDebug("总量:%.0lfMB 已用:%.0lfMB 空闲:%.0lfMB",lst[1].toDouble(),lst[2].toDouble(),lst[6].toDouble());
        Memory_=lst[2].toDouble()*100/lst[1].toDouble();
qDebug("%.0lfMB",Memory_);
        Memory=QString("%1%").arg(QString::number(Memory_ ,'f', 0));
        return true;
    }
    return false;
}

void LinuxSystemMethod::updateSpeed()
{ QProcess process;
    process.start("cat", QStringList() << "/proc/net/dev");
    if (!process.waitForStarted() || !process.waitForFinished()) {

        qDebug() << "Failed to execute command.";
        return; } // 读取命令输出
    QString result = process.readAllStandardOutput();
    // 解析输出，获取网络速度信息 // 这里仅是一个简单的示例，你可能需要根据具体的系统和需求进行解析 // 例如，从输出中提取关于特定网络接口的速度信息
    qDebug() << "Network Speed: " << result;
}
